package com.e3.basdoc.measure.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.e3.basdoc.measure.dao.MeasureUnitDAO;
import com.e3.basdoc.measure.entity.MeasureUnitEntity;
import com.e3.basdoc.measure.model.MeasureUnitModel;
import com.e3.basdoc.measure.model.MeasureUnitQC;
import com.e3.basdoc.measure.service.MeasureUnitCacheManager;
import com.e3.basdoc.measure.service.MeasureUnitQueryService;
import com.e3.core.base.DAOHelper;
import com.e3.core.base.ServiceException;
import com.e3.core.base.SuperQueryService;

public class MeasureUnitQueryServiceImpl extends SuperQueryService implements MeasureUnitQueryService {

	private MeasureUnitDAO measureDAO;
	
	private MeasureUnitDAO getMeasureUnitDAO(){
		if(measureDAO == null){
			measureDAO = DAOHelper.createDAOInstance(MeasureUnitDAO.class);
		}
		return measureDAO;
	}

	public List<MeasureUnitModel> getMeasureUnitByCondition(MeasureUnitQC qc) throws ServiceException {
		
		List<Long> ids = getMeasureUnitDAO().getMeasureUnitIdsByCondition(qc);
		if(ids == null||ids.isEmpty()){
			return null;
		}
		
		List<MeasureUnitModel> models = new ArrayList<MeasureUnitModel>(ids.size());
		for (Long id : ids) {
			MeasureUnitModel model = getMeasureUnitById(id);
			models.add(model);
		}
		return models;
	}
	/**
	 * the method is used to load data into cache.
	 */
	public List<MeasureUnitModel> getAllMeasureUnits() throws ServiceException {
		List<MeasureUnitEntity> entities = getMeasureUnitDAO().getAllMeasureUnits();
		if(entities==null||entities.isEmpty()){
			return null;
		}
		List<MeasureUnitModel> models = new ArrayList<MeasureUnitModel>(entities.size());
		for (MeasureUnitEntity measureEntity : entities) {
			models.add(measureEntityToModel(measureEntity));
		}
		return models;
	}

	public MeasureUnitModel getMeasureUnitById(long id) throws ServiceException {
		MeasureUnitModel model = MeasureUnitCacheManager.INSTANCE.get(id);
		if(model==null){
			MeasureUnitEntity entity = getMeasureUnitDAO().getById(MeasureUnitEntity.class, id);
			model = measureEntityToModel(entity);
			if(model != null){
				MeasureUnitCacheManager.INSTANCE.put(model);
			}
		}
		
		return model;
	}

	public List<MeasureUnitModel> getMeasureUnitByIds(List<Long> ids)	throws ServiceException {
		if(ids == null||ids.isEmpty()){
			return null;
		}
		
		List<MeasureUnitModel> models = new ArrayList<MeasureUnitModel>(ids.size());
		for (Long id : ids) {
			MeasureUnitModel model = getMeasureUnitById(id);
			models.add(model);
		}
		
		return models;
	}

	private MeasureUnitModel measureEntityToModel(MeasureUnitEntity entity){
		
		if(entity == null){
			return null;
		}
		
		MeasureUnitModel model = new MeasureUnitModel();
		model = entityToModel(model, entity);
		
		model.setCode(entity.getCode());
		model.setName(entity.getName());
		
		return model;
	}

}
